// 定义责任链模式相关的 trait 和结构体

// Handler trait，定义了设置下一个处理器和处理请求的方法
trait Handler {
    fn set_next(&mut self, next: Box<dyn Handler>) -> &mut dyn Handler;
    fn handle(&self, request: &str);
}

// 具体处理者 ConcreteHandlerA
struct ConcreteHandlerA {
    next: Option<Box<dyn Handler>>,
}

impl ConcreteHandlerA {
    fn new() -> Self {
        Self { next: None }
    }
}

// 实现 Handler trait 对于 ConcreteHandlerA 的方法
impl Handler for ConcreteHandlerA {
    fn set_next(&mut self, next: Box<dyn Handler>) -> &mut dyn Handler {
        self.next = Some(next);
        self
    }

    fn handle(&self, request: &str) {
        if request == "A" {
            println!("ConcreteHandlerA handled request: {}", request);
        } else if let Some(ref next) = self.next {
            next.handle(request);
        }
    }
}

// 具体处理者 ConcreteHandlerB
struct ConcreteHandlerB {
    next: Option<Box<dyn Handler>>,
}

impl ConcreteHandlerB {
    fn new() -> Self {
        Self { next: None }
    }
}

// 实现 Handler trait 对于 ConcreteHandlerB 的方法
impl Handler for ConcreteHandlerB {
    fn set_next(&mut self, next: Box<dyn Handler>) -> &mut dyn Handler {
        self.next = Some(next);
        self
    }

    fn handle(&self, request: &str) {
        if request == "B" {
            println!("ConcreteHandlerB handled request: {}", request);
        } else if let Some(ref next) = self.next {
            next.handle(request);
        }
    }
}

// 主函数入口
pub fn main() {
    let mut handler_a = ConcreteHandlerA::new(); // 创建 ConcreteHandlerA 实例
    let handler_b = ConcreteHandlerB::new(); // 创建 ConcreteHandlerB 实例

    // 设置责任链，将 handler_b 设置为 handler_a 的下一个处理者
    handler_a.set_next(Box::new(handler_b));

    // 处理各种请求
    handler_a.handle("A"); // 由 ConcreteHandlerA 处理
    handler_a.handle("B"); // 由 ConcreteHandlerB 处理
    handler_a.handle("C"); // 没有处理者处理
}
